<template>
  <div class="full-feature-demo" v-loading="loading">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
            <!-- Kafka环境选择器 -->
            <div class="instance-selector-compact">
              <el-select 
                :model-value="selectedConfigId" 
                placeholder="选择Kafka环境"
                @change="$emit('config-change', $event)"
                size="small"
                style="width: 280px"
              >
                <el-option
                  v-for="config in kafkaConfigs"
                  :key="config.id"
                  :label="`${config.config_name} (${config.host}:${config.port})`"
                  :value="config.id"
                />
              </el-select>
              
              <el-tag v-if="currentConfig" type="success" size="small">
                <el-icon><Connection /></el-icon>
                {{ currentConfig.config_name }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="Topic名称">
                <el-select
                  v-model="searchForm.topic_name"
                  placeholder="输入或选择topic"
                  clearable
                  filterable
                  style="width: 200px"
                >
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="topic in topicsList"
                    :key="topic"
                    :label="topic"
                    :value="topic"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 140px">
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="active" />
                  <el-option label="非活跃" value="inactive" />
                  <el-option label="仅监控" value="monitored_only" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="告警状态">
                <el-select v-model="searchForm.alert_status" placeholder="选择告警状态" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="正常" value="normal" />
                  <el-option label="告警中" value="alerting" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <!-- 1. 高级筛选 - info (灰色, plain) -->
              <el-button 
                type="info" 
                @click="advancedSearchExpanded = !advancedSearchExpanded" 
                plain
              >
                <el-icon>
                  <component :is="advancedSearchExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                高级筛选
              </el-button>
              
              <!-- 2. 字段设置 - info (灰色, plain) -->
              <el-button 
                type="info" 
                @click="showFieldSelector = !showFieldSelector" 
                plain
              >
                <el-icon>
                  <component :is="showFieldSelector ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                字段设置
              </el-button>
              
              <!-- 3. 搜索 - primary (蓝色) -->
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              
              <!-- 4. 重置 - warning (橙色) -->
              <el-button type="warning" @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              
              <!-- 5. 快捷操作 - success (绿色, plain) -->
              <el-button 
                type="success" 
                @click="quickActionsExpanded = !quickActionsExpanded" 
                plain
              >
                <el-icon>
                  <component :is="quickActionsExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                快捷操作
              </el-button>
            </div>
          </div>
          
          <!-- 高级筛选折叠区域 -->
          <transition name="advanced-filter">
            <div v-show="advancedSearchExpanded" class="advanced-filter-section">
              <div class="advanced-filter-fields">
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="searchForm.timeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :shortcuts="dateShortcuts"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 400px"
                    :teleported="true"
                    popper-class="datetime-picker-popper"
                    :clearable="true"
                  />
                </el-form-item>
              </div>
            </div>
          </transition>
          
          <!-- 字段设置折叠区域 -->
          <transition name="field-panel">
            <div v-show="showFieldSelector" class="field-selector-panel">
              <div class="field-sorter">
                <div class="sorter-header">
                  <h4>字段排序设置</h4>
                  <p class="sorter-description">使用上下箭头调整字段显示顺序，勾选要显示的字段</p>
                </div>
                
                <div class="field-list-sortable">
                  <div
                    v-for="(field, index) in sortedFields"
                    :key="field.value"
                    class="field-item"
                    :class="{ 'field-disabled': !selectedFields.includes(field.value) }"
                  >
                    <div class="field-drag-handle">
                      <span class="drag-icon">⋮⋮</span>
                    </div>
                    <el-checkbox
                      v-model="selectedFields"
                      :value="field.value"
                      :disabled="field.required"
                      class="field-checkbox"
                    >
                      <span class="field-label">{{ field.label }}</span>
                      <span v-if="field.required" class="required-mark">*</span>
                    </el-checkbox>
                    <div class="field-group-tag">
                      <el-tag size="small" :type="getGroupTagType(field.group)">
                        {{ getGroupTitle(field.group) }}
                      </el-tag>
                    </div>
                    <div class="field-sort-controls">
                      <el-button
                        size="small"
                        :disabled="index === 0"
                        @click="moveFieldUp(index)"
                        circle
                        type="primary"
                        plain
                      >
                        ↑
                      </el-button>
                      <el-button
                        size="small"
                        :disabled="index === sortedFields.length - 1"
                        @click="moveFieldDown(index)"
                        circle
                        type="primary"
                        plain
                      >
                        ↓
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 字段设置操作按钮 -->
              <div class="field-actions">
                <el-button type="primary" @click="saveCurrentFieldSettings">
                  <el-icon><Check /></el-icon>
                  保存设置
                </el-button>
                <el-button type="success" @click="setAsDefaultSettings">
                  <el-icon><Star /></el-icon>
                  设为默认
                </el-button>
                <el-button @click="resetFieldSettings">
                  <el-icon><Refresh /></el-icon>
                  重置默认
                </el-button>
                <el-button type="warning" @click="clearDefaultSettings">
                  <el-icon><Delete /></el-icon>
                  清除默认
                </el-button>
                <el-button @click="showFieldSelector = false">
                  <el-icon><Close /></el-icon>
                  关闭
                </el-button>
              </div>
            </div>
          </transition>
          
          <!-- 快捷操作折叠区域 -->
          <transition name="quick-actions">
            <div v-show="quickActionsExpanded" class="quick-actions-section">
              <div class="quick-actions-toolbar">
                <div class="toolbar-left">
                  <!-- ===== 有选中时：显示选中徽章 + 所有批量操作按钮 ===== -->
                  <template v-if="selectedMonitors.length > 0">
                    <!-- 选中徽章 -->
                    <div class="selected-info-inline">
                      <el-icon class="selected-icon"><Select /></el-icon>
                      <span>已选择 <strong>{{ selectedMonitors.length }}</strong> 条记录</span>
                    </div>
                    <el-divider direction="vertical" />
                    
                    <!-- 所有批量操作按钮（包含两类）-->
                    <div class="button-group">
                      <!-- 第一类：支持"全部/选中"模式的按钮（对话框内可选择范围）-->
                      <el-button type="primary" @click="showBatchUpdateAlert">
                        <el-icon><BellFilled /></el-icon>
                        批量更新告警配置 <!-- 对话框内可选"全部"或"仅选中" -->
                      </el-button>
                      
                      <!-- 第二类：仅操作选中项的按钮（无"全部"选项）-->
                      <el-button type="success" @click="handleBatchEnableMonitor">
                        <el-icon><View /></el-icon>
                        批量启用监控 <!-- 只针对选中的记录 -->
                      </el-button>
                      
                      <el-button type="info" @click="handleBatchQuery">
                        <el-icon><Search /></el-icon>
                        批量查询
                      </el-button>
                      
                      <!-- 演示批量操作对话框类型 -->
                      <el-dropdown trigger="click" @command="handleBatchDialogMenu">
                        <el-button type="warning" plain>
                          <el-icon><MoreFilled /></el-icon>
                          批量操作示例
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="confirm">
                              <el-icon><VideoPause /></el-icon>
                              确认型批量操作
                            </el-dropdown-item>
                            <el-dropdown-item command="config">
                              <el-icon><Setting /></el-icon>
                              配置型批量操作
                            </el-dropdown-item>
                            <el-dropdown-item command="complex">
                              <el-icon><Setting /></el-icon>
                              复杂配置型批量操作
                            </el-dropdown-item>
                            <el-dropdown-item command="progress">
                              <el-icon><Loading /></el-icon>
                              进度型批量操作
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                      
                      <!-- 消息提示示例 -->
                      <el-dropdown trigger="click" @command="handleMessageExample">
                        <el-button type="success" plain>
                          <el-icon><Bell /></el-icon>
                          消息提示示例
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="success">
                              <el-icon style="color: #67c23a;"><SuccessFilled /></el-icon>
                              成功消息
                            </el-dropdown-item>
                            <el-dropdown-item command="error">
                              <el-icon style="color: #f56c6c;"><Close /></el-icon>
                              错误消息
                            </el-dropdown-item>
                            <el-dropdown-item command="warning">
                              <el-icon style="color: #e6a23c;"><Warning /></el-icon>
                              警告消息
                            </el-dropdown-item>
                            <el-dropdown-item command="info">
                              <el-icon style="color: #909399;"><BellFilled /></el-icon>
                              信息消息
                            </el-dropdown-item>
                            <el-dropdown-item divided command="background">
                              <el-icon style="color: #409eff;"><Clock /></el-icon>
                              后台任务示例
                            </el-dropdown-item>
                            <el-dropdown-item command="batch-delete">
                              <el-icon style="color: #f56c6c;"><Delete /></el-icon>
                              批量删除（带确认）
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </template>
                  
                  <!-- 未选中时只显示支持"全部"模式的按钮 -->
                  <!-- ⚠️ 这些按钮在对话框内提供"更新全部/仅选中"的选项 -->
                  <template v-else>
                    <div class="button-group">
                      <!-- 示例：批量更新告警配置（对话框内可选"全部"或"仅选中"）-->
                      <el-button type="primary" @click="showBatchUpdateAlert">
                        <el-icon><BellFilled /></el-icon>
                        批量更新告警配置
                      </el-button>
                      
                      <!-- 添加其他支持"全部"模式的按钮 -->
                      <!-- 示例：数据统计、批量更新等 -->
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>监控列表（演示数据）</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper" @click="paginationExpanded = !paginationExpanded">
                  <span class="page-count">本页 {{ filteredMonitors.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">{{ currentPage }}/{{ Math.ceil(filteredMonitors.length / pageSize) || 1 }}</span>
                  <el-icon class="pagination-icon" :class="{ 'expanded': paginationExpanded }">
                    <ArrowDown />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        
        <div class="table-container">
          <el-table
            :data="paginatedMonitors"
            @selection-change="handleSelectionChange"
            @sort-change="handleSortChange"
            :default-sort="{ prop: 'last_alert_time', order: 'descending' }"
            style="width: 100%"
            :height="600"
          >
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column prop="topic_name" label="Topic名称" width="350" fixed="left">
              <template #default="{ row }">
                <div class="topic-name-cell">
                  <span class="topic-text">{{ row.topic_name }}</span>
                  <el-tooltip content="复制Topic名称" placement="top">
                    <el-button 
                      type="info"
                      size="small" 
                      @click="handleCopyTopicName(row.topic_name)" 
                      circle
                      class="copy-btn"
                    >
                      <el-icon><DocumentCopy /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="partition_id" label="分区ID" width="100" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.partition_id === -1" type="success" size="small">全部</el-tag>
                <span v-else>{{ row.partition_id }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="latest_offset" label="最新Offset" width="120" align="right">
              <template #default="{ row }">
                <el-tag size="small" type="info">{{ row.latest_offset }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="consumer_lag" label="消费滞后" width="110" align="right" sortable="custom">
              <template #default="{ row }">
                <el-tag 
                  :type="row.consumer_lag > 1000 ? 'danger' : row.consumer_lag > 100 ? 'warning' : 'success'" 
                  size="small"
                >
                  {{ row.consumer_lag }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="topic_size_bytes" label="Topic大小" width="120" align="right" sortable="custom">
              <template #default="{ row }">
                {{ formatBytes(row.topic_size_bytes) }}
              </template>
            </el-table-column>
            <el-table-column prop="message_key" label="消息Key" width="150" show-overflow-tooltip>
              <template #default="{ row }">
                <span v-if="row.message_key">{{ row.message_key }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="message_timestamp" label="最新消息时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.message_timestamp">{{ row.message_timestamp }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="alert_threshold_hours" label="告警阈值(小时)" width="130" align="center">
              <template #default="{ row }">
                <el-tag size="small">{{ row.alert_threshold_hours }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alert_count" label="告警次数" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.alert_count > 0 ? 'danger' : 'info'" size="small">
                  {{ row.alert_count }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="is_monitored" label="监控开关" width="100" align="center">
              <template #default="{ row }">
                <el-switch
                  v-model="row.is_monitored"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleToggleMonitor(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="is_alert_enabled" label="告警开关" width="100" align="center">
              <template #default="{ row }">
                <el-switch
                  v-model="row.is_alert_enabled"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleToggleAlert(row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="alert_status" label="告警状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getAlertStatusType(row.alert_status)" size="small">
                  {{ getAlertStatusText(row.alert_status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="last_alert_time" label="最后告警时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.last_alert_time">{{ row.last_alert_time }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="updated_at" label="更新时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.updated_at">{{ row.updated_at }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180" sortable="custom">
              <template #default="{ row }">
                <span v-if="row.created_at">{{ row.created_at }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <!-- 根据action_count动态显示按钮 -->
                  <!-- 1个按钮：查看详情（演示不同对话框类型） -->
                  <el-tooltip content="查看详情" placement="top">
                    <el-dropdown 
                      v-if="row.action_count >= 1" 
                      trigger="click"
                      @command="(cmd) => handleViewDetailMenu(cmd, row)"
                    >
                      <el-button type="primary" size="small" circle>
                        <el-icon><View /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="simple">
                            <el-icon><Document /></el-icon>
                            简单详情
                          </el-dropdown-item>
                          <el-dropdown-item command="simple-json">
                            <el-icon><DocumentCopy /></el-icon>
                            简单带JSON
                          </el-dropdown-item>
                          <el-dropdown-item command="grouped">
                            <el-icon><List /></el-icon>
                            分组详情
                          </el-dropdown-item>
                          <el-dropdown-item command="tabs">
                            <el-icon><Grid /></el-icon>
                            标签页详情
                          </el-dropdown-item>
                          <el-dropdown-item command="stats">
                            <el-icon><TrendCharts /></el-icon>
                            带统计详情
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </el-tooltip>
                  
                  <!-- 2个按钮：编辑配置（演示不同编辑表单类型） -->
                  <el-tooltip content="编辑配置" placement="top">
                    <el-dropdown 
                      v-if="row.action_count >= 2" 
                      trigger="click"
                      @command="(cmd) => handleEditMenu(cmd, row)"
                    >
                      <el-button type="warning" size="small" circle>
                        <el-icon><Edit /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="simple">
                            <el-icon><Edit /></el-icon>
                            简单表单
                          </el-dropdown-item>
                          <el-dropdown-item command="grouped">
                            <el-icon><Document /></el-icon>
                            分组表单
                          </el-dropdown-item>
                          <el-dropdown-item command="tabs">
                            <el-icon><List /></el-icon>
                            标签页表单
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </el-tooltip>
                  
                  <!-- 3个按钮：显示重置告警（如果有）或立即查询 -->
                  <template v-if="row.action_count >= 3">
                    <!-- 如果有告警中状态，显示重置告警 -->
                    <el-tooltip 
                      v-if="row.alert_status === 'alerting'" 
                      content="重置告警" 
                      placement="top"
                    >
                      <el-button type="success" size="small" @click="handleResetAlert(row)" circle>
                        <el-icon><Refresh /></el-icon>
                      </el-button>
                    </el-tooltip>
                    <!-- 否则显示立即查询（仅在action_count === 3时） -->
                    <el-tooltip v-else-if="row.action_count === 3" content="立即查询" placement="top">
                      <el-button type="info" size="small" @click="handleQueryNow(row)" circle>
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </template>
                  
                  <!-- 4个按钮：立即查询（当action_count === 4时） -->
                  <!-- 注意：如果alert_status === 'alerting'，重置告警按钮已经通过action_count >= 3条件显示 -->
                  <!-- 这里显示立即查询作为第4个按钮 -->
                  <el-tooltip v-if="row.action_count === 4" content="立即查询" placement="top">
                    <el-button type="info" size="small" @click="handleQueryNow(row)" circle>
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </el-tooltip>
                  
                  <!-- 超过4个按钮：显示第4个按钮 + 更多下拉菜单 -->
                  <template v-if="row.action_count > 4">
                    <!-- 第4个按钮：复制配置 -->
                    <el-tooltip content="复制配置" placement="top">
                      <el-button type="info" size="small" @click="handleCopyConfig(row)" circle>
                        <el-icon><DocumentCopy /></el-icon>
                      </el-button>
                    </el-tooltip>
                    
                    <!-- 更多操作下拉菜单 -->
                    <el-tooltip content="更多操作" placement="top">
                      <el-dropdown @command="(command) => handleMoreAction(command, row)" trigger="click">
                        <el-button type="info" size="small" circle>
                          <el-icon><MoreFilled /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item command="query">
                              <el-icon><Search /></el-icon>
                              立即查询
                            </el-dropdown-item>
                            <el-dropdown-item command="history">
                              <el-icon><Clock /></el-icon>
                              查看历史
                            </el-dropdown-item>
                            <el-dropdown-item command="export" divided>
                              <el-icon><Download /></el-icon>
                              导出数据
                            </el-dropdown-item>
                            <el-dropdown-item command="delete" divided>
                              <el-icon><Delete /></el-icon>
                              <span style="color: #f56c6c;">删除记录</span>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </el-tooltip>
                  </template>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页折叠区域 -->
        <transition name="pagination-slide">
          <div v-show="paginationExpanded" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredMonitors.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 详情对话框示例 -->
    <DetailDialogSimple
      v-model="showDetailDialogSimple"
      :data="currentMonitor"
    />
    <DetailDialogSimpleWithJson
      v-model="showDetailDialogSimpleWithJson"
      :data="currentMonitor"
    />
    <DetailDialogGrouped
      v-model="showDetailDialogGrouped"
      :data="currentMonitor"
    />
    <DetailDialogTabs
      v-model="showDetailDialogTabs"
      :data="currentMonitor"
    />
    <DetailDialogWithStats
      v-model="showDetailDialogWithStats"
      :data="currentMonitor"
    />
    
    <!-- 编辑对话框示例 -->
    <EditDialogSimple
      v-model="showEditDialogSimple"
      :data="currentMonitor"
      @success="handleEditSuccess"
    />
    <EditDialogGrouped
      v-model="showEditDialogGrouped"
      :data="currentMonitor"
      @success="handleEditSuccess"
    />
    <EditDialogTabs
      v-model="showEditDialogTabs"
      :data="currentMonitor"
      @success="handleEditSuccess"
    />
    
    <!-- 批量操作对话框示例 -->
    <BatchDialogConfirm
      v-model="showBatchDialogConfirm"
      :items="selectedMonitors"
      @success="handleBatchSuccess"
    />
    <BatchDialogConfig
      v-model="showBatchDialogConfig"
      :items="selectedMonitors"
      :total-count="filteredMonitors.length"
      @success="handleBatchSuccess"
    />
    <BatchDialogComplex
      v-model="showBatchDialogComplex"
      :items="selectedMonitors"
      @start-batch="handleStartBatchComplex"
    />
    <BatchDialogProgress
      ref="batchProgressRef"
      v-model="showBatchDialogProgress"
      :jobs="selectedMonitors.length > 0 ? selectedMonitors : []"
      @complete="handleBatchComplete"
      @background="handleBatchBackground"
    />
    
    <!-- 后台任务浮动按钮 - 右侧边栏样式 -->
    <transition name="slide-fade">
      <div
        v-if="hasBackgroundTask"
        class="background-task-indicator"
        :class="{ collapsed: !isSidebarExpanded }"
        :title="isSidebarExpanded ? '单击收起，双击查看详情' : '单击展开'"
      >
        <!-- 收起状态：只显示箭头 -->
        <div 
          v-if="!isSidebarExpanded" 
          class="arrow-icon"
          @click="isSidebarExpanded = true"
        >
          <el-icon><ArrowLeft /></el-icon>
        </div>
        
        <!-- 展开状态：显示完整内容 -->
        <div 
          v-else
          class="task-content-wrapper"
          @click="handleSingleClick"
          @dblclick="handleDoubleClick"
        >
          <div class="task-icon">
            <el-icon v-if="backgroundTaskCompleted" class="icon-success"><Check /></el-icon>
            <el-icon v-else class="icon-loading"><Loading /></el-icon>
          </div>
          <div class="task-text">
            <div class="task-label">{{ backgroundTaskCompleted ? '已完成' : '进行中' }}</div>
            <div class="task-progress">{{ backgroundTaskProgress }}</div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import taskNotifier from '@/utils/taskNotifier'
import {
  Search, Refresh, ArrowDown, ArrowUp, Select, BellFilled, View, Hide,
  Bell, TurnOff, Delete, List, DocumentCopy, CopyDocument, Edit, Connection,
  Check, Star, Close, MoreFilled, Clock, Download, TrendCharts, Document,
  VideoPause, Setting, Grid, Loading, Warning, SuccessFilled, ArrowLeft
} from '@element-plus/icons-vue'
import { mockMonitors, mockTopicsList, mockApiDelay, mockFieldConfig } from '../mock/data'
import { copyToClipboard } from '@/utils/clipboard'
// 对话框组件
import DetailDialogSimple from './DetailDialogSimple.vue'
import DetailDialogSimpleWithJson from './DetailDialogSimpleWithJson.vue'
import DetailDialogGrouped from './DetailDialogComplex.vue' // 重命名为分组详情
import DetailDialogTabs from './DetailDialogTabs.vue'
import DetailDialogWithStats from './DetailDialogWithStats.vue'
import EditDialogSimple from './EditDialogSimple.vue'
import EditDialogGrouped from './EditDialogGrouped.vue'
import EditDialogTabs from './EditDialogTabs.vue'
import BatchDialogConfirm from './BatchDialogConfirm.vue'
import BatchDialogConfig from './BatchDialogConfig.vue'
import BatchDialogComplex from './BatchDialogComplex.vue'
import BatchDialogProgress from './BatchDialogProgress.vue'

const props = defineProps({
  kafkaConfigs: {
    type: Array,
    default: () => []
  },
  selectedConfigId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['config-change'])

// 数据
const loading = ref(false)
const monitors = ref([...mockMonitors])
const topicsList = ref(mockTopicsList)
const selectedMonitors = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const paginationExpanded = ref(false)
const advancedSearchExpanded = ref(false)
const showFieldSelector = ref(false)
const quickActionsExpanded = ref(false)
// 排序状态
const sortField = ref('last_alert_time')
const sortOrder = ref('desc')
// 详情对话框状态
const showDetailDialogSimple = ref(false)
const showDetailDialogSimpleWithJson = ref(false)
const showDetailDialogGrouped = ref(false)
const showDetailDialogTabs = ref(false)
const showDetailDialogWithStats = ref(false)
// 编辑对话框状态
const showEditDialogSimple = ref(false)
const showEditDialogGrouped = ref(false)
const showEditDialogTabs = ref(false)
// 批量操作对话框状态
const showBatchDialogConfirm = ref(false)
const showBatchDialogConfig = ref(false)
const showBatchDialogComplex = ref(false)
const showBatchDialogProgress = ref(false)
const batchProgressRef = ref(null)
// 当前选中的监控对象
const currentMonitor = ref(null)
// 后台任务状态
const hasBackgroundTask = ref(false) // 默认隐藏，只在点击"后台运行"时显示
const backgroundTaskProgress = ref('0/0')
const backgroundTaskCompleted = ref(false)
const isSidebarExpanded = ref(true)
const clickTimer = ref(null)

const searchForm = reactive({
  topic_name: '',
  status: '',
  is_monitored: null,
  is_alert_enabled: null,
  alert_status: '',
  timeRange: null
})

// 时间快捷选项
const dateShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(start.getHours() - 1)
      return [start, end]
    }
  },
  {
    text: '最近6小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(start.getHours() - 6)
      return [start, end]
    }
  },
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '昨天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 1)
      start.setHours(0, 0, 0, 0)
      end.setDate(end.getDate() - 1)
      end.setHours(23, 59, 59, 999)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    }
  }
]

// 设置默认时间范围：今天0点到当前时刻
const setDefaultTimeRange = () => {
  const now = new Date()
  const startOfToday = new Date()
  startOfToday.setHours(0, 0, 0, 0)
  
  // 格式化为 YYYY-MM-DD HH:mm:ss
  const formatDateTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  searchForm.timeRange = [formatDateTime(startOfToday), formatDateTime(now)]
}

// 移除 batchAlertForm，使用 BatchDialogConfig 组件

// 字段设置相关
const allFields = computed(() => {
  return [
    ...mockFieldConfig.basic,
    ...mockFieldConfig.status,
    ...mockFieldConfig.time,
    ...mockFieldConfig.other
  ]
})

const selectedFields = ref([
  'id',
  'topic_name',
  'partition_id',
  'status',
  'alert_status',
  'message_timestamp',
  'last_alert_time',
  'latest_offset'
])

const fieldOrder = ref([...selectedFields.value])

const sortedFields = computed(() => {
  return fieldOrder.value
    .map(value => allFields.value.find(f => f.value === value))
    .filter(Boolean)
    .map(field => ({
      ...field,
      group: getFieldGroup(field.value)
    }))
})

const getFieldGroup = (value) => {
  if (mockFieldConfig.basic.find(f => f.value === value)) return 'basic'
  if (mockFieldConfig.status.find(f => f.value === value)) return 'status'
  if (mockFieldConfig.time.find(f => f.value === value)) return 'time'
  return 'other'
}

const getGroupTitle = (group) => {
  const map = {
    basic: '基础信息',
    status: '状态信息',
    time: '时间信息',
    other: '其他信息'
  }
  return map[group] || '其他'
}

const getGroupTagType = (group) => {
  const map = {
    basic: 'primary',
    status: 'success',
    time: 'warning',
    other: 'info'
  }
  return map[group] || 'info'
}

const moveFieldUp = (index) => {
  if (index > 0) {
    const fields = [...fieldOrder.value]
    const [removed] = fields.splice(index, 1)
    fields.splice(index - 1, 0, removed)
    fieldOrder.value = fields
  }
}

const moveFieldDown = (index) => {
  if (index < fieldOrder.value.length - 1) {
    const fields = [...fieldOrder.value]
    const [removed] = fields.splice(index, 1)
    fields.splice(index + 1, 0, removed)
    fieldOrder.value = fields
  }
}

const saveCurrentFieldSettings = () => {
  ElMessage.success('字段设置已保存（演示模式）')
}

const setAsDefaultSettings = () => {
  localStorage.setItem('field_settings_default', JSON.stringify({
    fields: selectedFields.value,
    order: fieldOrder.value
  }))
  ElMessage.success('已设为默认设置（演示模式）')
}

const resetFieldSettings = () => {
  const saved = localStorage.getItem('field_settings_default')
  if (saved) {
    const data = JSON.parse(saved)
    selectedFields.value = [...data.fields]
    fieldOrder.value = [...data.order]
    ElMessage.success('已重置为默认设置（演示模式）')
  } else {
    ElMessage.info('未找到默认设置')
  }
}

const clearDefaultSettings = () => {
  localStorage.removeItem('field_settings_default')
  ElMessage.success('已清除默认设置（演示模式）')
}

const currentConfig = computed(() => {
  return props.kafkaConfigs.find(c => c.id === props.selectedConfigId)
})

// 筛选后的数据
const filteredMonitors = computed(() => {
  let result = [...monitors.value]
  
  if (searchForm.topic_name) {
    result = result.filter(m => m.topic_name === searchForm.topic_name)
  }
  if (searchForm.status) {
    result = result.filter(m => m.status === searchForm.status)
  }
  if (searchForm.alert_status) {
    result = result.filter(m => m.alert_status === searchForm.alert_status)
  }
  if (searchForm.is_monitored !== null) {
    result = result.filter(m => m.is_monitored === searchForm.is_monitored)
  }
  if (searchForm.is_alert_enabled !== null) {
    result = result.filter(m => m.is_alert_enabled === searchForm.is_alert_enabled)
  }
  
  return result
})

// 分页后的数据
const paginatedMonitors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredMonitors.value.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.success('筛选完成（演示模式）')
}

const handleReset = () => {
  Object.assign(searchForm, {
    topic_name: '',
    status: '',
    is_monitored: null,
    is_alert_enabled: null,
    alert_status: ''
  })
  // 重置时间范围为默认值（今天0点到当前时刻）
  setDefaultTimeRange()
  currentPage.value = 1
  ElMessage.success('重置完成')
}

// ========== 消息提示示例 ==========

// 后台任务示例（模拟长时间运行的任务）
const handleLongRunningTask = async () => {
  // 记录任务开始
  taskNotifier.saveTaskStart({
    name: '批量数据统计',
    type: 'batch_statistics',
    timestamp: Date.now()
  })
  
  try {
    // 显示后台运行消息
    ElMessage({
      message: '✨ 任务已在后台运行，完成后将自动通知',
      type: 'success',
      duration: 3000,
      showClose: true,
      grouping: true
    })
    
    // 模拟API调用（实际应该调用真实API）
    await mockApiDelay(3000)
    
    // 模拟任务成功结果
    const result = {
      processed_tables: 15,
      success_tables: 14,
      failed_tables: 1,
      elapsed_seconds: 3.2
    }
    
    // 保存任务结果
    taskNotifier.saveTaskResult('批量数据统计', result, true)
    // 立即显示通知
    taskNotifier.checkAndNotify()
    
    // 刷新数据
    await handleRefresh()
  } catch (error) {
    console.error('任务失败:', error)
    taskNotifier.saveTaskResult('批量数据统计', error.message, false)
    taskNotifier.checkAndNotify()
  }
}

// 批量删除示例（带确认对话框）
const handleBatchDeleteWithConfirm = async () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要删除的监控项')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMonitors.value.length} 个监控项吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 模拟批量删除
    await mockApiDelay(1500)
    
    const successCount = selectedMonitors.value.length - 1
    const failCount = 1
    
    // 批量操作消息规范
    if (failCount > 0) {
      ElMessage.warning(`成功 ${successCount} 个，失败 ${failCount} 个`)
    } else {
      ElMessage.success(`成功删除 ${successCount} 个监控项`)
    }
    
    selectedMonitors.value = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
    // 用户点击取消，不显示任何消息
  }
}

const handleRefresh = async () => {
  loading.value = true
  await mockApiDelay(800)
  loading.value = false
  ElMessage.success('刷新完成（演示模式）')
}

const handleSelectionChange = (selection) => {
  selectedMonitors.value = selection
}

// 排序变化处理
const handleSortChange = ({ prop, order }) => {
  if (prop) {
    sortField.value = prop
    sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
    
    // 实际场景中应该调用loadData()重新加载数据
    // 这里演示本地排序
    sortDataLocally()
    
    ElMessage.info(`已按 ${getFieldLabel(prop)} ${order === 'ascending' ? '升序' : '降序'} 排序`)
  }
}

// 本地排序（演示用）
const sortDataLocally = () => {
  const field = sortField.value
  const order = sortOrder.value
  
  monitors.value.sort((a, b) => {
    let aVal = a[field]
    let bVal = b[field]
    
    // 处理空值
    if (aVal === null || aVal === undefined) aVal = ''
    if (bVal === null || bVal === undefined) bVal = ''
    
    // 数字类型比较
    if (typeof aVal === 'number' && typeof bVal === 'number') {
      return order === 'asc' ? aVal - bVal : bVal - aVal
    }
    
    // 字符串类型比较
    const aStr = String(aVal)
    const bStr = String(bVal)
    
    if (order === 'asc') {
      return aStr.localeCompare(bStr)
    } else {
      return bStr.localeCompare(aStr)
    }
  })
}

// 获取字段标签（用于消息提示）
const getFieldLabel = (field) => {
  const fieldMap = {
    'topic_name': 'Topic名称',
    'partition_id': '分区ID',
    'consumer_lag': '消费滞后',
    'topic_size_bytes': 'Topic大小',
    'message_timestamp': '最新消息时间',
    'latest_offset': '最新偏移量',
    'committed_offset': '已提交偏移量',
    'alert_count': '告警次数',
    'last_alert_time': '最后告警时间',
    'updated_at': '更新时间',
    'created_at': '创建时间'
  }
  return fieldMap[field] || field
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleToggleMonitor = async (row) => {
  if (row.is_monitored === 0) {
    row.is_alert_enabled = 0
    row.status = 'inactive'
  } else {
    row.status = row.is_alert_enabled === 1 ? 'active' : 'monitored_only'
  }
  ElMessage.success('监控开关已更新（演示模式）')
}

const handleToggleAlert = async (row) => {
  if (row.is_monitored === 0 && row.is_alert_enabled === 1) {
    ElMessage.warning('请先开启监控开关')
    row.is_alert_enabled = 0
    return
  }
  row.status = row.is_monitored === 1 
    ? (row.is_alert_enabled === 1 ? 'active' : 'monitored_only')
    : 'inactive'
  ElMessage.success('告警开关已更新（演示模式）')
}

// 详情对话框菜单处理
const handleViewDetailMenu = (command, row) => {
  currentMonitor.value = { ...row }
  switch (command) {
    case 'simple':
      showDetailDialogSimple.value = true
      break
    case 'simple-json':
      // 为JSON示例添加消息数据
      currentMonitor.value = {
        ...row,
        request_body: row.request_body || {
          pageNo: 4,
          pageSize: 100,
          cat: 201582301,
          sort: 'total_sales_des',
          adzoneId: 115821550410
        },
        response_body: row.response_body || {
          code: 1,
          message: '操作成功'
        },
        trace_id: row.trace_id || 'b7fcb1584e954c2e8bdee35048bcddc3',
        log_path: row.log_path || '/mnt/data/bigdata/datacenter/prod/yc-cps-api/logs/yc-cps-api.log',
        service_name: row.service_name || 'yc-cps-api',
        api_path: row.api_path || row.topic_name || '/tb/materialOptionalUpgrade',
        message: row.message || 'API access completed successfully'
      }
      showDetailDialogSimpleWithJson.value = true
      break
    case 'grouped':
      showDetailDialogGrouped.value = true
      break
    case 'tabs':
      showDetailDialogTabs.value = true
      break
    case 'stats':
      showDetailDialogWithStats.value = true
      break
  }
}

// 编辑对话框菜单处理
const handleEditMenu = (command, row) => {
  currentMonitor.value = { ...row }
  switch (command) {
    case 'simple':
      showEditDialogSimple.value = true
      break
    case 'grouped':
      showEditDialogGrouped.value = true
      break
    case 'tabs':
      showEditDialogTabs.value = true
      break
  }
}

// 原有的handleViewDetail保留为快速查看（简单详情）
const handleViewDetail = (row) => {
  currentMonitor.value = { ...row }
  showDetailDialogSimple.value = true
}

const handleEdit = (row) => {
  ElMessage.info('编辑功能演示（演示模式）')
}

const handleQueryNow = (row) => {
  ElMessage.success(`正在查询 ${row.topic_name} 的最新数据...（演示模式）`)
}

const handleCopyTopicName = async (topicName) => {
  await copyToClipboard(topicName, 'Topic名称', false)
  ElMessage.success(`Topic名称已复制: ${topicName}`)
}

const handleCopyJson = async () => {
  const jsonText = formatJsonMessage(currentMonitor.value.latest_message)
  await copyToClipboard(jsonText, 'JSON内容')
}

const formatJsonMessage = (message) => {
  if (!message) return '暂无消息内容'
  try {
    return JSON.stringify(message, null, 2)
  } catch (e) {
    return typeof message === 'string' ? message : JSON.stringify(message)
  }
}

const getAlertStatusType = (status) => {
  const typeMap = {
    'normal': 'success',
    'alerting': 'danger'
  }
  return typeMap[status] || 'info'
}

const getAlertStatusText = (status) => {
  const textMap = {
    'normal': '正常',
    'alerting': '告警中'
  }
  return textMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    'active': 'success',
    'inactive': 'info',
    'monitored_only': 'warning'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'active': '活跃',
    'inactive': '非活跃',
    'monitored_only': '仅监控'
  }
  return textMap[status] || status
}

// 批量操作处理
// ⚠️ 示例：支持"全部/选中"模式的按钮（无需检查是否有选中）
const showBatchUpdateAlert = () => {
  // 不检查选中数量，直接打开对话框
  // 对话框内部会根据 selectedMonitors.length 提供"仅选中"或"全部"的选项
  showBatchDialogConfig.value = true
}

const handleBatchSuccess = () => {
  ElMessage.success('批量操作成功（演示模式）')
  selectedMonitors.value = []
}

const handleEditSuccess = () => {
  ElMessage.success('编辑成功（演示模式）')
}

// ========== 整合模式：通用操作按钮（无选中时显示） ==========

const handleQuickRefresh = () => {
  ElMessage.success('一键刷新完成（演示模式）')
}

const handleFetchLatest = () => {
  ElMessage.info('获取最新数据中...（演示模式）')
  setTimeout(() => {
    ElMessage.success('数据已更新（演示模式）')
  }, 1000)
}

const handleBatchComplete = (result) => {
  ElMessage.success(`批量操作完成：成功 ${result.success} 条，失败 ${result.failure} 条（演示模式）`)
  selectedMonitors.value = []
}

const handleBatchBackground = (progress) => {
  // 关闭进度对话框
  showBatchDialogProgress.value = false
  
  // 从进度参数中获取信息
  const { current, total, successCount, failureCount } = progress
  
  // 显示后台任务侧边栏
  hasBackgroundTask.value = true
  backgroundTaskProgress.value = `${current}/${total}`
  backgroundTaskCompleted.value = false
  isSidebarExpanded.value = true
  
  // 显示后台运行消息
  ElMessage({
    message: '✨ 任务已在后台运行，完成后将自动通知',
    type: 'success',
    duration: 3000,
    showClose: true,
    grouping: true
  })
  
  // 继续模拟任务进度（演示用）
  continueTaskProgress(current, total)
}

// 消息提示示例菜单处理
const handleMessageExample = (command) => {
  switch (command) {
    case 'success':
      ElMessage.success('操作成功！这是一条成功消息')
      break
    case 'error':
      ElMessage.error('操作失败！这是一条错误消息')
      break
    case 'warning':
      ElMessage.warning('请先选择记录！这是一条警告消息')
      break
    case 'info':
      ElMessage.info('正在加载数据...这是一条信息消息')
      break
    case 'background':
      handleLongRunningTask()
      break
    case 'batch-delete':
      handleBatchDeleteWithConfirm()
      break
  }
}

// 批量操作对话框菜单处理
const handleBatchDialogMenu = (command) => {
  if (selectedMonitors.value.length === 0 && command !== 'progress') {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  
  switch (command) {
    case 'confirm':
      showBatchDialogConfirm.value = true
      break
    case 'config':
      showBatchDialogConfig.value = true
      break
    case 'complex':
      showBatchDialogComplex.value = true
      break
    case 'progress':
      // 进度对话框可以没有选中项时演示
      showBatchDialogProgress.value = true
      break
  }
}

// 复杂配置型批量操作开始处理
const handleStartBatchComplex = ({ items, params }) => {
  // 关闭配置对话框
  showBatchDialogComplex.value = false
  
  // 打开进度对话框并开始模拟批量操作
  showBatchDialogProgress.value = true
  
  // 模拟批量操作进度
  ElMessage.info(`开始批量操作，共 ${items.length} 项（演示模式）`)
}

const handleBatchComplexConfig = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  showBatchDialogComplex.value = true
}

// handleBatchUpdateAlertConfig 已移除，由 BatchDialogConfig 组件处理

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchEnableMonitor = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`已启用 ${selectedMonitors.value.length} 条记录的监控（演示模式）`)
}

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchDisableMonitor = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`已禁用 ${selectedMonitors.value.length} 条记录的监控（演示模式）`)
}

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchEnableAlert = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`已启用 ${selectedMonitors.value.length} 条记录的告警（演示模式）`)
}

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchDisableAlert = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`已禁用 ${selectedMonitors.value.length} 条记录的告警（演示模式）`)
}

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchQuery = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`批量查询完成（演示模式，${selectedMonitors.value.length}条）`)
}

// ⚠️ 示例：只操作选中项的按钮（需要检查是否有选中）
const handleBatchDelete = () => {
  if (selectedMonitors.value.length === 0) {
    ElMessage.warning('请先选择要操作的记录')
    return
  }
  ElMessage.success(`已删除 ${selectedMonitors.value.length} 条记录（演示模式）`)
  selectedMonitors.value = []
}

const handleResetAlert = (row) => {
  ElMessage.success(`已重置 ${row.topic_name} 的告警状态（演示模式）`)
  row.alert_status = 'normal'
  row.alert_count = 0
  row.last_alert_time = null
}

const handleCopyConfig = (row) => {
  ElMessage.success(`已复制 ${row.topic_name} 的配置（演示模式）`)
}

const handleMoreAction = (command, row) => {
  switch (command) {
    case 'query':
      handleQueryNow(row)
      break
    case 'history':
      ElMessage.info(`查看 ${row.topic_name} 的历史记录（演示模式）`)
      break
    case 'export':
      ElMessage.success(`导出 ${row.topic_name} 的数据（演示模式）`)
      break
    case 'delete':
      ElMessage.warning(`删除 ${row.topic_name} 的记录（演示模式）`)
      break
    default:
      ElMessage.info(`执行操作: ${command}（演示模式）`)
  }
}

const formatBytes = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// ========== 后台任务侧边栏交互 ==========

// 处理单击事件（收起侧边栏）
const handleSingleClick = () => {
  // 清除之前的定时器
  if (clickTimer.value) {
    clearTimeout(clickTimer.value)
  }
  
  // 延迟300ms执行收起操作（避免与双击冲突）
  clickTimer.value = setTimeout(() => {
    isSidebarExpanded.value = false
    clickTimer.value = null
  }, 300)
}

// 处理双击事件（打开进度对话框）
const handleDoubleClick = () => {
  // 取消单击的延迟执行
  if (clickTimer.value) {
    clearTimeout(clickTimer.value)
    clickTimer.value = null
  }
  
  // 立即打开进度对话框
  showBatchDialogProgress.value = true
  ElMessage.info('已打开任务详情（演示模式）')
}

// 继续后台任务进度（从当前进度开始）
const continueTaskProgress = (startCurrent, total) => {
  let current = startCurrent
  
  const interval = setInterval(() => {
    current++
    backgroundTaskProgress.value = `${current}/${total}`
    
    // 同时更新进度对话框（如果重新打开）
    if (batchProgressRef.value && showBatchDialogProgress.value) {
      // 这里可以继续更新对话框的进度
    }
    
    if (current >= total) {
      clearInterval(interval)
      backgroundTaskCompleted.value = true
      
      // 3秒后自动隐藏
      setTimeout(() => {
        hasBackgroundTask.value = false
      }, 3000)
      
      ElMessage.success('✅ 后台任务完成：成功处理' + total + '个任务')
    }
  }, 2000) // 每2秒更新一次
}

// ========== 表格多选与快捷操作联动 ==========

// 监听选中项变化，自动展开/折叠快捷操作
watch(() => selectedMonitors.value.length, (newLength) => {
  if (newLength > 0) {
    // 有选中时，自动展开快捷操作
    quickActionsExpanded.value = true
  } else {
    // 取消选中时，自动折叠快捷操作
    quickActionsExpanded.value = false
  }
})

// 生命周期钩子
onMounted(() => {
  // 设置默认时间范围
  setDefaultTimeRange()
  
  // 页面加载时检查待通知的任务
  taskNotifier.checkAndNotify()
  
  // 请求浏览器通知权限（可选）
  taskNotifier.requestPermission()
  
  // 不再自动启动任务，只在用户点击"后台运行"时才显示侧边栏
})
</script>

<style scoped>
/* 组件容器 - 在标签页中使用时，需要添加顶部间距 */
.full-feature-demo {
  margin-top: 20px;  /* 标签页内容区域从标签栏下方20px开始，与Reports页面保持一致 */
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 24px;
}

.search-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;  /* 深灰色文字 - Element Plus text-primary */
}

.search-title .el-icon {
  color: #409eff;  /* 蓝色图标 - Element Plus primary */
}

.instance-selector-compact {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  display: flex;
  gap: 16px;
  flex: 1;
}

.search-form-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 高级筛选折叠区域 - 无背景色，只有顶部边框 */
.advanced-filter-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

/* 快捷操作折叠区域 - 无背景色，只有顶部边框 */
.quick-actions-section {
  margin-top: 16px;
  padding: 16px;
  border-top: 2px solid #409eff;
  border-radius: 8px;
}

.advanced-filter-fields {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.advanced-filter-fields .el-form-item {
  margin-bottom: 0;
}

.quick-actions-toolbar {
  display: flex;
  justify-content: flex-start;
}

.quick-actions-toolbar .toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.quick-actions-toolbar .button-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.quick-actions-toolbar .el-divider--vertical {
  height: 24px;
  margin: 0 8px;
  border-color: #e4e7ed;
}

.quick-actions-toolbar .el-button {
  border-radius: 6px;
  font-weight: 500;
}

/* 选中信息徽章样式 */
.selected-info-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 6px;
  color: #1976d2;
  font-size: 14px;
  font-weight: 500;
}

.selected-icon {
  color: #1976d2;
  font-size: 16px;
}

.selected-info-inline strong {
  color: #0d47a1;
  font-size: 16px;
}

/* 表格样式 */
.table-section {
  margin-bottom: 24px;
}

.table-card {
  border-radius: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;  /* 深灰色文字 - Element Plus text-primary */
}

.table-title .el-icon {
  color: #409eff;  /* 蓝色图标 - Element Plus primary */
}

.table-header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 刷新按钮样式 */
.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-icon.expanded {
  transform: rotate(180deg);
}

.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

.topic-name-cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.copy-btn {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.topic-name-cell:hover .copy-btn {
  opacity: 1;
}

.action-buttons {
  display: flex;
  gap: 12px;  /* 基础间距：12px */
  flex-wrap: nowrap;
  white-space: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.action-buttons .el-button {
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
  width: 32px;  /* 固定宽度 */
  height: 32px;  /* 固定高度 */
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.action-buttons .el-button:active {
  transform: translateY(0) scale(0.98);
}

.action-buttons .el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #66B3FF 100%);
  border: none;
}

.action-buttons .el-button--warning {
  background: linear-gradient(135deg, #E6A23C 0%, #F0C78A 100%);
  border: none;
}

.action-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #B1B3B8 100%);
  border: none;
}

/* 确保所有包装元素不影响间距 - 只重置上下和右的 margin，保留左 margin 用于控制间距 */
.action-buttons > * {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
  margin-right: 0 !important;
  margin-left: 0;
  padding: 0;
  display: inline-flex;
}

/* 确保 el-tooltip 包装元素不影响间距 */
.action-buttons > :deep(.el-tooltip) {
  display: inline-flex;
  margin-top: 0 !important;
  margin-bottom: 0 !important;
  margin-right: 0 !important;
  margin-left: 0;
  padding: 0;
}

.action-buttons :deep(.el-tooltip__trigger) {
  display: inline-flex;
  margin: 0 !important;
  padding: 0;
}

/* 确保 el-dropdown 不影响间距 */
.action-buttons :deep(.el-dropdown) {
  display: inline-flex;
  margin: 0 !important;
  padding: 0;
}

/* 为第4个及以后的按钮添加额外左边距，使其与前3个按钮有更明显的视觉分隔 */
/* 这样前3个按钮之间是 12px（gap），第3个和第4个之间是 12px（gap）+ 8px（margin）= 20px */
/* 注意：当 action_count > 4 时，第5个按钮是"更多操作"，也需要额外间距 */
.action-buttons > :nth-child(n+4) {
  margin-left: 8px !important;
}

/* 下拉菜单内部按钮样式 */
.action-buttons .el-dropdown .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0;
}

.text-muted {
  color: #909399;
}

/* 字段设置面板样式 - 与Jobs页面保持一致 */
.field-selector-panel {
  border-top: 1px solid #e4e7ed;  /* 只有顶部边框 */
  padding-top: 16px;               /* 上内边距 */
  margin-top: 16px;                /* 上外边距 */
  /* 注意：不使用背景色、圆角、完整边框 */
}

.field-sorter {
  margin-bottom: 16px;
}

.sorter-header {
  margin-bottom: 16px;
}

.sorter-header h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.sorter-description {
  margin: 0;
  color: #606266;
  font-size: 13px;
}

.field-list-sortable {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.2s;
}

.field-item:hover {
  background: #f0f2f5;
  border-color: #c0c4cc;
}

.field-item.field-disabled {
  opacity: 0.5;
}

.field-drag-handle {
  cursor: grab;
}

.drag-icon {
  color: #909399;
  font-size: 14px;
  font-weight: bold;
}

.field-checkbox {
  flex: 1;
}

.field-label {
  margin-left: 8px;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}

.field-group-tag {
  flex-shrink: 0;
}

.field-sort-controls {
  display: flex;
  gap: 4px;
}

.field-sort-controls .el-button {
  width: 28px;
  height: 28px;
  padding: 0;
}

.field-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background-color: #fafafa;
  margin-top: 16px;
  flex-wrap: wrap;
}

.field-actions .el-button {
  margin: 2px;
}

/* 折叠动画 */
.advanced-filter-enter-active,
.advanced-filter-leave-active,
.field-panel-enter-active,
.field-panel-leave-active,
.quick-actions-enter-active,
.quick-actions-leave-active,
.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.advanced-filter-enter-from,
.advanced-filter-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.advanced-filter-enter-to,
.advanced-filter-leave-from {
  opacity: 1;
  max-height: 200px;
  margin-top: 16px;
  padding-top: 16px;
}

.field-panel-enter-from,
.field-panel-leave-to,
.quick-actions-enter-from,
.quick-actions-leave-to,
.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.quick-actions-enter-to,
.quick-actions-leave-from {
  opacity: 1;
  max-height: 300px;
  margin-top: 16px;
  padding-top: 16px;
}

.field-panel-enter-active,
.field-panel-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.field-panel-enter-from,
.field-panel-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.field-panel-enter-to,
.field-panel-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 1000px;
}

/* JSON查看器 */
.json-viewer {
  margin-top: 12px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.json-viewer pre {
  margin: 0;
  padding: 16px;
  overflow-x: auto;
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 13px;
  line-height: 1.6;
}

/* ========== 后台任务浮动按钮样式 ========== */
.background-task-indicator {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px 12px;
  background: linear-gradient(180deg, rgba(64, 158, 255, 0.95) 0%, rgba(102, 179, 255, 0.95) 100%);
  border-radius: 8px 0 0 8px;
  box-shadow: -4px 0 16px rgba(64, 158, 255, 0.4);
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 60px;
  overflow: hidden;
}

.background-task-indicator:hover {
  box-shadow: -6px 0 20px rgba(64, 158, 255, 0.6);
  transform: translateY(-50%) translateX(-4px);
}

.background-task-indicator:active {
  transform: translateY(-50%) translateX(-2px);
}

/* 收起状态 */
.background-task-indicator.collapsed {
  min-width: 32px;
  padding: 12px 8px;
}

.background-task-indicator.collapsed:hover {
  transform: translateY(-50%) translateX(-6px);
}

/* 箭头图标 */
.arrow-icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  animation: pulse-arrow 2s ease-in-out infinite;
  cursor: pointer;
}

/* 展开内容包装器 */
.task-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

@keyframes pulse-arrow {
  0%, 100% { 
    opacity: 1;
    transform: translateX(0);
  }
  50% { 
    opacity: 0.7;
    transform: translateX(-3px);
  }
}

.task-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.25);
  color: white;
  font-size: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.icon-success {
  animation: pulse 2s ease-in-out infinite;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

.task-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  writing-mode: vertical-rl;
  text-orientation: upright;
}

.task-label {
  font-size: 12px;
  font-weight: 600;
  color: white;
  letter-spacing: 2px;
  line-height: 1;
}

.task-progress {
  font-size: 11px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  letter-spacing: 1px;
  line-height: 1;
}

/* 滑动淡入淡出动画 */
.slide-fade-enter-active {
  transition: all 0.4s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateY(-50%) translateX(100%);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-50%) translateX(100%);
}
</style>

<style>
/* 时间选择器弹出层优化（全局样式，不使用scoped） */
/* 确保时间选择面板正确显示在日期输入框上层 */
.datetime-picker-popper {
  z-index: 3000 !important;
}

.datetime-picker-popper .el-picker-panel__body {
  min-height: 380px;
}

.datetime-picker-popper .el-date-range-picker__time-header {
  position: relative;
  z-index: 1;
}

.datetime-picker-popper .el-picker-panel__content {
  margin: 0;
}

/* 确保时间选择面板不被日期面板遮挡 */
.datetime-picker-popper .el-time-panel {
  position: absolute;
  z-index: 2 !important;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 优化日期时间范围选择器的布局 */
.datetime-picker-popper.el-popper {
  transform-origin: center top !important;
}
</style>

